package com.example.smart_video.ui.activity;

import static com.example.smart_video.model.Constants.TENCENT_BUCKET;
import static com.example.smart_video.model.Constants.TENCENT_BUCKET_OFFICE_URL;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.databinding.DataBindingUtil;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.example.cleandemo3.R;
import com.example.cleandemo3.databinding.ActivityUploadVideoBinding;
import com.example.smart_video.model.Constants;
import com.example.smart_video.model.json.CommonRootBean;
import com.example.smart_video.model.json.VideoClassData;
import com.example.smart_video.model.json.VideoData;
import com.example.smart_video.utils.CommonUtils;
import com.wink_172.library.LibApplication;
import com.wink_172.library.activity.SmartActivity;
import com.wink_172.library.callback.ICallback;
import com.wink_172.library.model.json.CustomEventBus;
import com.wink_172.library.utils.DateUtil;
import com.wink_172.library.utils.FileUtil;
import com.wink_172.library.utils.ImageUtil;
import com.wink_172.library.utils.TencentCosUtils;
import com.wink_172.library.view.ActionBarView;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;
import java.util.SortedMap;
import java.util.UUID;

public class UploadVideoActivity extends SmartActivity {


    public ActivityUploadVideoBinding binding;

    private String mLocalVideoUrl = "";//视频本地地址
    private String mLocalThumbnail = "";//略缩图本地地址
    private String mWebVideoUrl = "";//视频地址
    private String mWebThumbnail = "";//略缩图地址

    private String name;
    private String width;
    private String height;
    private String rotation;
    private long duration;

    private VideoClassData classData;//选中的分类
    private VideoData videoData;
    private static final String TAG = "UploadVideoActivity";
    private String[] PERMISSIONS = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
    };

    public static void startActivity(Context context, Object... args) {
        Intent intent = new Intent(context, UploadVideoActivity.class);

        if (args.length > 0) {
            intent.putExtra(com.wink_172.library.model.Constants.PARAM_DATA1, (VideoData) args[0]);
        }

        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_upload_video);
        binding.setOnClickListener(this);

        initView();

        init();

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    private void init() {
        binding.btnTop.setActivated(false);

        videoData = (VideoData) getIntent().getSerializableExtra(com.wink_172.library.model.Constants.PARAM_DATA1);

        if (videoData != null) {
            String thumb = TENCENT_BUCKET_OFFICE_URL + videoData.getThumbnail();
            x.image().bind(binding.image, thumb);
            queryVideoInfo("" + videoData.getId());
            ((ActionBarView) binding.actionBar).updateAllContent(R.mipmap.icon_nav_arrow, "当前视频id:" + videoData.getId(), "提交");
            binding.btnVideoUpload.setVisibility(View.GONE);

        } else {
            ((ActionBarView) binding.actionBar).updateAllContent(R.mipmap.icon_nav_arrow, "上传视频", "提交");
            binding.btnDelete.setVisibility(View.GONE);
            binding.btnDown.setVisibility(View.GONE);

        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        String url = "";
        switch (v.getId()) {
            case R.id.btn_top: {
                boolean check = binding.btnTop.isActivated();
                binding.btnTop.setActivated(!check);
            }
            break;

            case R.id.btn_down:
                DownLoadActivity.startActivity(this, mWebVideoUrl);
                break;

            case R.id.btn_delete:
                showConfirmDialog();
                break;

            case R.id.sel_view:
                SelectClassActivity.startActivity(this, com.wink_172.library.model.Constants.ACTIVITY_REQUEST_CODE3002);
                break;

            case R.id.btn_video:///播放视频
                if (videoData != null) {
                    String video_url = TENCENT_BUCKET_OFFICE_URL + videoData.getVideo_url();
                    VideoPlayActivity.Companion.startActivity(getActivity(), 0, video_url);
                }
                break;

            case R.id.btn_video_upload://选择视频
                if (!checkPermissions(PERMISSIONS)) {
                    requestPermissions(com.wink_172.library.model.Constants.ACTIVITY_REQUEST_CODE3003, PERMISSIONS);

                } else {
//                    CommonUtils.showToast("暂时不提供上传功能");
                    startPickVideo();
                }
                break;


        }
    }

    public void initView() {
        ((ActionBarView) binding.actionBar).setCallback(new ActionBarView.ICallback() {
            @Override
            public void onSendEvent(int event, String content) {
                if (event == ActionBarView.LEFT_BTN) {
                    finish();

                } else if (event == ActionBarView.RIGHT_BTN) {

                    if (!TextUtils.isEmpty(mLocalVideoUrl)) {
                        uploadFile(mLocalVideoUrl, 1);
                    } else {
                        if (videoData != null && classData != null) {
                            saveVideoInfo();
                        }
                    }


                }
            }
        });

    }


    /**
     * 选择视频
     */
    private void startPickVideo() {
        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
        intent.setType("video/*");//不加筛选条件可以包含图片
        startActivityForResult(intent, com.wink_172.library.model.Constants.ACTIVITY_REQUEST_CODE3001);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent resultIt) {
        super.onActivityResult(requestCode, resultCode, resultIt);
        if (resultCode != Activity.RESULT_OK) {
            return;
        }


        switch (requestCode) {
            case com.wink_172.library.model.Constants.ACTIVITY_REQUEST_CODE3002:
                classData = (VideoClassData) resultIt.getSerializableExtra(com.wink_172.library.model.Constants.PARAM_DATA1);
                binding.selView.setText(classData.getName());
                break;

            case com.wink_172.library.model.Constants.ACTIVITY_REQUEST_CODE3001:
                classData = null;//置空
                binding.selView.setText("");


                Uri selectedVideo = resultIt.getData();
                String[] filePathColumn = {MediaStore.Video.Media.DATA};

                Cursor cursor = getContentResolver().query(selectedVideo,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                mLocalVideoUrl = cursor.getString(columnIndex);
                Log.e(TAG, "onActivityResult: ====>>videoPath:" + mLocalVideoUrl);
                cursor.close();


                Bitmap bitmap = com.wink_172.library.utils.CommonUtils.getVideoThumbnail(mLocalVideoUrl, 100, 100, MediaStore.Images.Thumbnails.MINI_KIND);
                mLocalThumbnail = com.wink_172.library.model.Constants.savePath + com.wink_172.library.model.Constants.ThumbnailImageName;

                FileUtil.Companion.createFolder(com.wink_172.library.model.Constants.savePath);
                boolean result = FileUtil.Companion.createFile(mLocalThumbnail);

                if (!result) {
                    hideProgressDialog();
                    com.wink_172.library.utils.CommonUtils.showToast("本地路径不存在");
                    return;
                }

                ImageUtil.saveBitmapFile3(bitmap, mLocalThumbnail);
                ((ImageView) binding.btnVideo).setImageBitmap(bitmap);

                MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                retriever.setDataSource(mLocalVideoUrl);
                width = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH); //宽
                height = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT); //高
                rotation = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);//视频的方向角度
                duration = Long.valueOf(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));//视频的长度  毫秒

                binding.videoInfoView.setText("duration:" + duration);
                break;

        }
    }


    @Override
    public void handlerCallBack(Message msg) {
        super.handlerCallBack(msg);
        switch (msg.what) {

        }
    }


    /**
     * 保存视频信息
     */
    private void saveVideoInfo() {
        String input_name = binding.inputView.getText().toString();
        String input_content = binding.inputContentView.getText().toString();
        boolean top = binding.btnTop.isActivated();


        String url = Constants.BASE_URL + "video_action/savevideo";
        SortedMap<String, Object> parameters = CommonUtils.getBaseSortedMap();
        if (videoData != null) {
            parameters.put("id", "" + videoData.getId());
        }

        parameters.put("top", top ? "1" : "-1");
        parameters.put("name", input_name);
        parameters.put("show", "0" );
        parameters.put("author", "");
        parameters.put("video_url", mWebVideoUrl);

        if (!TextUtils.isEmpty(width) && !TextUtils.isEmpty(height)) {
            parameters.put("width", width);
            parameters.put("height", height);

        }

        if (!TextUtils.isEmpty(rotation)) {
            parameters.put("rotation", rotation);
        }
        if (duration > 0) {
            parameters.put("duration", "" + duration);
        }
//        parameters.put("image_url", );

        if (!TextUtils.isEmpty(input_content)) {
            parameters.put("content", input_content);
        }

        if (classData != null) {
            parameters.put("classfyId", "" + classData.getId());
        }
        parameters.put("thumbnail", mWebThumbnail);
        RequestParams params = CommonUtils.getTargetRequest(url, parameters);
        Log.e(TAG, "saveVideoInfo: ====>>" + params.toString());


        Callback.CommonCallback commonCallback = new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                hideProgressDialog();
                CommonRootBean commonRootBean = JSON.parseObject(result, CommonRootBean.class);
                if (commonRootBean.getCode() == 200) {
                    com.wink_172.library.utils.CommonUtils.showToast("保存成功");


                    copyFile(mLocalThumbnail, mWebThumbnail);
                    copyFile(mLocalVideoUrl, mWebVideoUrl);

//                FileUtil.delete(mLocalThumbnail);
                    FileUtil.Companion.delete(mLocalVideoUrl);

                    hideProgressDialog();


                    if (videoData == null) {
                        MainActivity.startActivity(UploadVideoActivity.this);

                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e(TAG, "onError: ====>>" + ex.toString());

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {


            }
        };

        x.http().post(params, commonCallback);

    }


    /**
     * 视频信息
     */
    private void queryVideoInfo(String id) {
        String url = Constants.BASE_URL + "video_action/videodetail";
        SortedMap<String, Object> parameters = CommonUtils.getBaseSortedMap();
        parameters.put("id", id);

        RequestParams params = CommonUtils.getTargetRequest(url, parameters);


        Callback.CommonCallback commonCallback = new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                CommonRootBean commonRootBean = JSON.parseObject(result, CommonRootBean.class);


                videoData = JSON.parseObject(commonRootBean.getData(), VideoData.class);
                classData = new VideoClassData();
                classData.setId(Integer.parseInt(videoData.getClassfyId()));

                mWebVideoUrl = videoData.getVideo_url();
                mWebThumbnail = videoData.getThumbnail();

                binding.inputView.setText(videoData.getName());
                binding.inputContentView.setText(videoData.getContent());
                if (!TextUtils.isEmpty(videoData.getClassfyId())) {
                    binding.selView.setText("当前分类id:" + videoData.getClassfyId());
                }


                binding.btnTop.setActivated(TextUtils.equals("1", videoData.getTop()));
                x.image().bind((ImageView) binding.btnVideo,
                        com.wink_172.library.model.Constants.TENCENT_BUCKET_WINK_URL + videoData.getThumbnail());
                binding.videoInfoView.setText("duration:" + videoData.getDuration());

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {


            }
        };
        x.http().get(params, commonCallback);

    }

    /**
     * 删除视频数据信息
     */
    private void deleteVideo(String id) {
        String url = Constants.BASE_URL + "video_action/videodelete";
        SortedMap<String, Object> parameters = CommonUtils.getBaseSortedMap();
        parameters.put("id", id);

        RequestParams params = CommonUtils.getTargetRequest(url, parameters);
        Log.e(TAG, "deleteVideo: ====>>" + params.toString());

        Callback.CommonCallback commonCallback = new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                CommonRootBean commonRootBean = JSON.parseObject(result, CommonRootBean.class);
                if (commonRootBean.getCode() == 200) {
                    FileUtil.Companion.delete(CommonUtils.getTargetUrl(mWebVideoUrl));
                    com.wink_172.library.utils.CommonUtils.showToast("删除成功");

                    finish();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e(TAG, "onError: ====>>" + ex.toString());

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {


            }
        };
        x.http().post(params, commonCallback);

    }

    /**
     * 拷贝文件
     */
    private boolean copyFile(String source, String destine) {
        String target = CommonUtils.getTargetUrl(destine);
        return org.xutils.common.util.FileUtil.copy(source, target);
    }


    /**
     * 确定弹窗
     */
    private void showConfirmDialog() {
        final Dialog dialog = new Dialog(this, R.style.CustomProgressDialog);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setContentView(com.wink_172.library.R.layout.dialog_common);
        dialog.getWindow().getAttributes().gravity = Gravity.CENTER;
        dialog.show();

        TextView title_view = dialog.findViewById(R.id.title_view);
        TextView content_view = dialog.findViewById(R.id.content_view);
        ImageView btn_close = dialog.findViewById(R.id.btn_right);
        TextView btn_left = dialog.findViewById(R.id.btn_cancel);
        TextView btn_right = dialog.findViewById(R.id.btn_confirm);

        content_view.setText("确定删除?");

        btn_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        btn_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();

            }
        });
        btn_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                deleteBucketFile();
            }
        });

    }

    /**
     * UUID  文件名
     * type       1视频  2视频略缩图
     * filePath 本地文件的绝对路径
     * <p>
     * 请注意任何上传文件均不能带有中文名称，否则删除腾讯云会失败（虽然提示成功但实际上未成功）    a5d85b7QQ空间视频_20210514183635.mp4
     */
    private void uploadFile(String filePath, final int type) {
        Log.e(TAG, "uploadFile: ====>>" + filePath);

        showProgressDialog();


        String childFolder;

        if (type == 1) {
            name = UUID.randomUUID().toString();//确保视频和图片名称一致
        }


        childFolder = DateUtil.longToString(System.currentTimeMillis(),
                DateUtil.FORMAT_DATE) + "/";


        String cosPath = com.wink_172.library.model.Constants.TENCENT_OSS_PACKAGE_NAME_video_all + childFolder + name + "." +
                FileUtil.Companion.getExtensionName(filePath);
        ; //对象在存储桶中的位置标识符，即称对象键

        TencentCosUtils.uploadTectentFile(cosPath, filePath, TENCENT_BUCKET,

                new com.wink_172.library.callback.ICallback() {
                    @Override
                    public void onSendEvent(int event, @NonNull Object... objects) {
                        if (event == com.wink_172.library.model.Constants.EventEnum.上传成功.ordinal()) {


                            if (type == 1) {
                                mWebVideoUrl = "/" + cosPath;
                                uploadFile(mLocalThumbnail, 2);

                            } else if (type == 2) {
                                mWebThumbnail = "/" + cosPath;
                                saveVideoInfo();
                            }

                        } else if (event == com.wink_172.library.model.Constants.EventEnum.上传失败.ordinal()) {
                            hideProgressDialog();
                        }

                    }
                }
        );


    }

    /**
     * 删除在线文件
     * *请注意任何上传文件均不能带有中文名称，否则删除腾讯云会失败（虽然提示成功但实际上未成功）    a5d85b7QQ空间视频_20210514183635.mp4
     * https://fun4demo-1254407438.cos.ap-guangzhou.myqcloud.com
     */
    private void deleteBucketFile() {
        List<String> objectList = new ArrayList<String>();

        Log.e(TAG, "deleteBucketFile: ====>>" + videoData.getVideo_url());

//        if (Constants.TEST_MODEL) {
//            objectList.add("/video-all/testfolder/abc.txt"); //对象在存储桶中的位置标识符，即对象键
//            objectList.add("/video-all/testfolder/Test.db"); //对象在存储桶中的位置标识符，即对象键
//
//        } else {
        objectList.add(videoData.getVideo_url()); //对象在存储桶中的位置标识符，即对象键
//            objectList.add(videoData.getImage_url()); //对象在存储桶中的位置标识符，即对象键
        objectList.add(videoData.getThumbnail()); //对象在存储桶中的位置标识符，即对象键


        TencentCosUtils.deleteBucketFile(objectList, TENCENT_BUCKET,
                new com.wink_172.library.callback.ICallback() {
                    @Override
                    public void onSendEvent(int event, @NonNull Object... objects) {

                        Log.e(TAG, "onSendEvent: ====>>01" );
                        if (event == com.wink_172.library.model.Constants.EventEnum.网络请求成功.ordinal()) {
                            Log.e(TAG, "onSendEvent: ====>>02" );
                            deleteVideo("" + videoData.getId());
                        } else if (event == com.wink_172.library.model.Constants.EventEnum.网络请求错误.ordinal()) {
                            Log.e(TAG, "onSendEvent: ====>>03" );
                        }
                    }
                });


    }
}